#include "Particle.h"

Particle::Particle()
{
    //初始化坐标
    x = 0;
    y = 0;
    nowFrameIndex = 0;
    //初始化速率
    xVel = 0;
    yVel = 0;
    setClips();
    filename = "../assert/particle.png";
    background = loadImage(filename);
}

Particle::~Particle()
{
    if( background != NULL )
    {
        SDL_FreeSurface( background ); 
    }
}



void Particle::move()
{
    //将圆点左右移动
    x += xVel;
    //将圆点上下移动
    y += yVel;
}

void Particle::show(SDL_Surface *screen)
{
    SDL_Rect offset;
    offset.x =  x + ( rand() % 30 - 15);
    offset.y =  y + ( rand() % 30 - 15);
    nowFrameIndex = rand() % 4;
    SDL_BlitSurface( background, &clips[nowFrameIndex], screen, &offset );
}


void Particle::setBackground(string filename)
{
    background = loadImage(filename);
}


void Particle::setPos(int x, int y)
{
    this->x = x;
    this->y = y;
}
void Particle::getPos(int &x, int &y)
{
    x = this->x;
    y = this->y;
}


void Particle::adaptPos(int w, int h)
{
    if( this->x < 0 )
    {
        this->x = 0;
    }
    else if( this->x > (w-PARTICLE_WIDTH) )
    {
        this->x = w-PARTICLE_WIDTH;
    }

    if( this->y < 0 )
    {
        this->y = 0;
    }
    else if( this->y > (h-PARTICLE_HEIGHT) )
    {
        this->y = h-PARTICLE_HEIGHT;
    }
}


void Particle::setClips()
{
    //剪切子图
    for ( int i = 0; i < PARTICLE_COUNT; i++ )
    {
        clips[ i ].x = PARTICLE_WIDTH * i;
        clips[ i ].y = 0;
        clips[ i ].w = PARTICLE_WIDTH;
        clips[ i ].h = PARTICLE_HEIGHT;
    }
}

SDL_Surface * Particle::loadImage( string filename ) 
{
    SDL_Surface* loadedImage = NULL;

    //加载图像
    loadedImage = IMG_Load( filename.c_str() );
    //如果图像优化成功
    if( loadedImage != NULL )
    {
        //映射关键色 0x26ea21
        Uint32 colorkey = SDL_MapRGB( loadedImage->format, 0x26, 0xea, 0x21 );
        //将所有颜色为（R 0, G 0xFF, B 0xFF）的像素设为透明。
        SDL_SetColorKey( loadedImage, SDL_SRCCOLORKEY, colorkey );
    }

    //返回优化后的表面
    return loadedImage;
}
